<template>
  <!-- 配件出库添加配件页面 -->
  <div>
    <template v-if="!editMode">
      <TopFilter ref="formPanel" :list="topFilterList" :cols="3" :labelWidth="90" @filterChange="searchAdjustOrderAdd"></TopFilter>
      <FilterTable
        ref="table"
        :height="'200'"
        :columns="columns"
        columnsRef="partPartOutboundAdjustOutboundAdjustOrderAdd"
        :fetchapi="fetchApi1"
        :params="fetchParams1"
        :datakey="'rows'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
        :onEnterEvent="handleDoubleClick"
        selectionType="single"
        :isSelectColumn="false"
        :dataSource="resetTableData"
      ></FilterTable>
    </template>

    <FormPanel ref="form" :list="form" :cols="3" :labelWidth="90" formType="add" :isSubmitBtn="false" @formChange="searchAdjustOrderAddTwo"></FormPanel>

    <FilterTable
      ref="table2"
      height="200"
      columnsRef="partPartOutboundAdjustOutboundAdjustOrderAdd1"
      :dataSource="activeData"
      :columns="columns2"
      :onColumnsChange="columns => (this.columns2 = columns)"
      :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      selectionType="single"
      :isSelectColumn="false"
    ></FilterTable>

    <div class="fixBtmBtn">
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button type="primary" :disabled="!activeData.length" @click="saveDialog">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { isAuthorized } from '@/utils/index';
import { queryPartForAdd, getStorageList, queryPartDetail, saveOutboundOrderCreate, queryAllocateInList } from '@/api/part/partOutbound/adjustOutbound/index';
import { getfindStorageCode } from '@/api/part/inventoryManager/inventoryManager/index';
import { getBrand } from '@/api/repair/basicParameters';
import { getBrandList } from '@/api/common/cars/masterDataCars';
import { dictionary } from '@/utils/dictMixin';
import { jsonToHump, formatdate, notifyAction } from '@/utils';
import { findAllRepair } from '@/api/repair/basicParameters';
import { queryTex } from '@/api/part/common';
export default {
  name: 'AdjustOrderAdd',
  mixins: [dictionary],
  props: {
    editMode: {
      type: Boolean,
      default: false
    },
    editData: Object,
    priceRate: {
      type: Number,
      default: 1
    },
    tax: {
      type: String,
      default: 0.13
    },
    billNo: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTablelist(),
      form: this.createForm(),
      columns2: this.createTablelist2(),
      fetchApi1: queryPartForAdd,
      fetchParams1: { xhrAbort: true },
      storageList: [],
      addBtnState: false,
      activeData: [], // 选中的数据（为数组，兼顾下方table显示）
      resetTableData: [], // 上方table数据（绑定重置用）
      billNoQuantity: 0
    };
  },
  computed: {
    /* 出库价格 */
    totalPrice() {
      return (this.form.find(item => item.fieldName == 'OUT_PRICE').initialValue * this.form.find(item => item.fieldName == 'OUT_QUANTITY').initialValue).toFixed(2);
      // this.form.find(item => item.fieldName == 'priceCoefficient').initialValue *
    }
  },
  watch: {
    totalPrice(newVal, oldVal) {
      this.form.find(item => item.fieldName == 'OUT_AMOUNT').initialValue = newVal;
    }
  },
  created() {
    this.getSrorageList();
    // 借进对应单查询
    this.queryBillNo();
    if (!this.editMode) {
      // this.findAllRepair();
    }
    if (this.editData.STORAGE_CODE) {
      this.$nextTick(() => {
        this.initEditData();
      });
    }
    // this.priceData = this.editData;
  },
  mounted() {
    this.getTax();
  },
  methods: {
    async getTax() {
      if (!this.tax) {
        let res = await queryTex();
        this.tax = res.data;
      }
    },
    async queryBillNo() {
      // 还入
      if (this.editData.ALLOCATE_TYPE && this.editData.ALLOCATE_TYPE == '82121004') {
        let res = await queryAllocateInList({ billNo: this.billNo });
        console.log(this.editData, res, '查询结果');
        if (res.resultCode == 200) {
          if (res.data.rows && res.data.rows.length > 0) {
            // this.billNoQuantity = res.data.rows[0].OUT_QUANTITY;
            this.billNoQuantity = res.data.rows.find(item => item.PART_NO == this.editData.PART_NO).OUT_QUANTITY;
          } else {
            this.billNoQuantity = this.editData.OUT_QUANTITY;
            // console.log('借出仓库数量', this.billNoQuantity);
          }
        }
        // this.billNoQuantity = this.editRowData.IN_QUANTITY;
      }
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo'
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT',
          label: '拼音',
          fieldName: 'spellCode'
        },
        {
          type: 'INPUT',
          label: '名称',
          fieldName: 'partName'
        },
        {
          type: 'SELECT',
          label: '配件类别',
          fieldName: 'partGroupCode',
          itemList: this.createDictList('8075')
        },
        {
          type: 'INPUT',
          label: '库位',
          fieldName: 'storagePositionCode'
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark'
        }
      ];
    },
    createTablelist() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input',
          width: 150,
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          filter: true,
          filterType: 'input',
          width: 150,
          showOverflowTooltip: true
        },
        {
          title: '含税销售价',
          dataIndex: 'SALES_PRICE',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税成本价',
          dataIndex: 'COST_PRICE',
          precision: 2,
          sorter: true,
          hidden: !isAuthorized('1313', '13131005'),
          filter: true,
          filterType: 'number'
        },
        {
          title: '替代配件',
          dataIndex: 'replacePart',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createForm() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          disabled: true,
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          readonly: true,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          readonly: true,
          disabled: true
        },
        {
          type: 'SELECT',
          label: '价格类型',
          fieldName: 'priceType',
          initialValue: 80501002,
          itemList: this.createDictList('8050'),
          change: val => {
            this.handlePriceCHange(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          rules: [{ required: true, message: '请输入价格系数', trigger: 'blur' }],
          initialValue: this.priceRate,
          precision: 2,
          fieldName: 'priceCoefficient',
          change: val => {
            this.handlePriceRate(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '出库单价',
          initialValue: 0,
          precision: 2,
          fieldName: 'OUT_PRICE'
        },
        {
          type: 'INPUT_NUMBER',
          label: '出库数量',
          initialValue: 1,
          precision: 2,
          fieldName: 'OUT_QUANTITY'
        },
        {
          type: 'INPUT',
          label: '出库金额',
          initialValue: 0.0,
          disabled: true,
          fieldName: 'OUT_AMOUNT',
          readonly: true
        }
      ];
    },
    createTablelist2() {
      return [
        {
          title: '含税销售价',
          dataIndex: 'COST_SALES_PRICE',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '索赔价',
          dataIndex: 'CLAIM_PRICE',
          precision: 2,
          sorter: true,
          hidden: !isAuthorized('1313', '13131006'),
          filter: true,
          filterType: 'number'
        },
        {
          title: '终端建议零售价格',
          dataIndex: 'INSURANCE_PRICE',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最低销售限价',
          dataIndex: 'minLimitedPrice',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '销售限价',
          dataIndex: 'LIMIT_PRICE',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最大库存',
          dataIndex: 'MAX_STOCK',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最小库存',
          dataIndex: 'MIN_STOCK',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '锁定量',
          dataIndex: 'LOCKED_QUANTITY',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '替代配件',
          dataIndex: 'OPTION_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '替代件库存',
          dataIndex: 'replacementInventory',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件类别',
          dataIndex: 'accessoriesCategory',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    getStroageName(STORAGE_CODE) {
      const item = this.storageList.find(x => {
        return x.value == STORAGE_CODE;
      });
      return item ? item.text : '';
    },
    async findAllRepair() {
      const resdata = await findAllRepair();
      this.topFilterList.find(x => x.fieldName === 'storageCode').initialValue = resdata.data['1100'];
      if (resdata.data['1061'] != null && resdata.data['1061'] != '' && resdata.data['1061'] != undefined) {
        this.form.find(x => x.fieldName === 'priceType').initialValue = Number(resdata.data['1061']);
      }
    },
    // 获取仓库列表
    async getSrorageList() {
      let resd = await getfindStorageCode();
      this.storageList = resd.data.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME }));
      this.topFilterList.find(item => item.fieldName == 'storageCode').itemList = this.storageList;
      this.form.find(item => item.fieldName == 'STORAGE_CODE').itemList = this.storageList;
      const res = await getBrand();
      this.topFilterList.find(item => item.fieldName == 'brand').itemList = res.data.map(x => ({ text: x.BRAND_NAME, value: x.BRAND_CODE + '' }));
      this.topFilterList.find(x => x.fieldName === 'brand').initialValue = res.data.find(item => item.BRAND_NAME == '奥迪').BRAND_CODE + '';
    },
    // 初始化编辑数据
    initEditData() {
      // console.log('初始化编辑数据', this.editData);
      this.form.find(item => item.fieldName == 'STORAGE_CODE').initialValue = this.editData.STORAGE_CODE;
      this.form.find(item => item.fieldName == 'PART_NO').initialValue = this.editData.PART_NO;
      this.form.find(item => item.fieldName == 'PART_NAME').initialValue = this.editData.PART_NAME;
      this.form.find(item => item.fieldName == 'OUT_PRICE').initialValue = this.editData.OUT_PRICE; // 出库价格
      this.form.find(item => item.fieldName == 'OUT_AMOUNT').initialValue = this.editData.OUT_AMOUNT; // 出库金额
      this.form.find(item => item.fieldName == 'OUT_QUANTITY').initialValue = this.editData.OUT_QUANTITY; // 出库数量
      if (this.editData.ITEM_ID == null || this.editData.ITEM_ID == '') {
        this.form.find(item => item.fieldName == 'priceCoefficient').initialValue = this.editData.priceCoefficient; // this.editData.OUT_AMOUNT / this.editData.OUT_QUANTITY / this.editData.OUT_PRICE || 0;
      } else {
        this.form.find(item => item.fieldName == 'priceCoefficient').initialValue = this.editData.OUT_AMOUNT / this.editData.OUT_QUANTITY / this.editData.OUT_PRICE || 0;
      }
      this.queryPartDetailByParnNo(this.editData);

      this.activeData = [this.editData];
    },
    // 查询
    queryClick() {
      let params = this.$refs.formPanel.SUBMIT_FORM();
      this.fetchParams1 = { ...params, xhrAbort: false };
      this.$nextTick(() => {
        this.fetchParams1.xhrAbort = true;
      });
    },
    // 重置
    resetClick() {
      this.$refs.formPanel.RESET_FORM();
      this.$refs.form.RESET_FORM();
      this.activeData = [];
      this.resetTableData = [];
    },
    // 双击列表项
    async handleDoubleClick(e) {
      if (e.STOCK_QUANTITY <= 0) {
        return notifyAction('配件账面库存为0不能借出', 'warning');
      }
      let data = e;
      this.form.find(item => item.fieldName == 'STORAGE_CODE').initialValue = data.STORAGE_CODE;
      this.form.find(item => item.fieldName == 'PART_NO').initialValue = data.PART_NO;
      this.form.find(item => item.fieldName == 'PART_NAME').initialValue = data.PART_NAME;
      // console.log('双击列表', e);
      this.queryPartDetailByParnNoTwo(data);
    },
    // 根据仓库以及配件编号查询配件详细信息two
    async queryPartDetailByParnNoTwo(e) {
      console.log(e, '1111');
      let _this = this;
      try {
        _this.$refs.table2.START_LOADING();
        let res = await queryPartDetail(e.PART_NO, e.STORAGE_CODE);
        _this.$refs.table2.STOP_LOADING();
        // _this.form.find(item => item.fieldName == 'OUT_PRICE').initialValue = res.data.rows[0].SALES_PRICE;
        _this.activeData = [res.data.rows[0]];
        let valData = _this.form.find(item => item.fieldName == 'priceType').initialValue;
        _this.handlePriceCHange(valData);
      } catch (err) {
        console.log(err);
        _this.$refs.table2.STOP_LOADING();
      }
    },
    // 根据仓库以及配件编号查询配件详细信息
    async queryPartDetailByParnNo(e) {
      console.log(e, '1111');
      let _this = this;
      console.log(this.$refs);
      try {
        _this.$refs.table2.START_LOADING();
        let res = await queryPartDetail(e.PART_NO, e.STORAGE_CODE);
        _this.$refs.table2.STOP_LOADING();
        // _this.form.find(item => item.fieldName == 'OUT_PRICE').initialValue = res.data.rows[0].SALES_PRICE;
        _this.activeData = [res.data.rows[0]];
      } catch (err) {
        console.log(err);
        _this.$refs.table2.STOP_LOADING();
      }
    },
    // 替换件
    replaceClick() {},
    // 价格系数变化
    handPriceRateCHange(val) {
      let priceType = this.form.find(item => item.fieldName == 'priceType').initialValue;
      let price = 0,
        priceData = this.activeData[0];
      console.log(priceData, 'priceData');
      switch (priceType) {
        case 80501001: // 成本价
          price = priceData.COST_PRICE.toFixed(2);
          break;
        case 80501002: // 销售价
          price = priceData.SALES_PRICE.toFixed(2);
          break;
        case 80501003: // 索赔价
          price = priceData.CLAIM_PRICE.toFixed(2);
          break;
        case 80501004: // 网点价
          price = priceData.NODE_PRICE.toFixed(2);
          break;
        case 80501005: // 最新进货价
          price = priceData.LATEST_PRICE.toFixed(2);
          break;
        case 80501006: // 含税成本价
          // price = priceData.SALES_PRICE;
          break;
        case 80501007: // 终端建议零售价格
          price = priceData.INSURANCE_PRICE.toFixed(2);
          break;
        case 80501008: // 建议销售价
          price = priceData.NOT_TAX_INSTRUCT_PRICE.toFixed(2);
          break;
        case 80501009: // 销售限价
          price = priceData.LIMIT_PRICE.toFixed(2);
          break;
        case 80501010 /* 含税采购价 */:
          price = priceData.PLAN_PRICE.toFixed(2);
          break;
        case 80501011 /* 含税采购价 */:
          price = priceData.COST_WHOLESALES_PRICE.toFixed(2);
          break;
        default:
          price = 0.0;
      }
      this.form.find(item => item.fieldName == 'OUT_PRICE').initialValue = price * val;
    },
    // 价格类型变化修改价格
    handlePriceCHange(val) {
      let priceType = val;
      let price = 0,
        priceData = this.activeData[0] ? this.activeData[0] : this.editData;
      console.log(priceData, 'priceData2', val);
      switch (priceType) {
        case 80501001 /* 成本价 */:
          price = Number(priceData.COST_PRICE).toFixed(2);
          break;
        case 80501002 /* 销售价 */:
          price = Number(priceData.COST_SALES_PRICE).toFixed(2);
          break;
        case 80501003 /* 索赔价 */:
          price = priceData.CLAIM_PRICE.toFixed(2);
          break;
        case 80501004 /* 网点价 */:
          price = priceData.NODE_PRICE.toFixed(2);
          break;
        case 80501005 /* 最新进货价 */:
          price = priceData.LATEST_PRICE.toFixed(2);
          break;
        case 80501006 /* 含税成本价 */:
          price = (priceData.COST_PRICE * (1 + Number(this.tax))).toFixed(2);
          break;
        case 80501007 /* 终端建议零售价格 */:
          price = priceData.INSURANCE_PRICE.toFixed(2);
          break;
        case 80501008 /* 建议销售价 */:
          price = priceData.INSTRUCT_PRICE.toFixed(2);
          break;
        case 80501009 /* 销售限价 */:
          price = priceData.LIMIT_PRICE.toFixed(2);
          break;
        case 80501010 /* 含税采购价 */:
          price = Number(priceData.PLAN_PRICE * (1 + (Number(this.tax) || 0.13))).toFixed(2);
          break;
        case 80501011 /* 含税批发价 */:
          price = Number(priceData.COST_WHOLESALES_PRICE ? priceData.COST_WHOLESALES_PRICE : 0).toFixed(2);
          break;
        default:
          price = 0.0;
      }

      // this.form.find(item => item.fieldName == 'OUT_PRICE').initialValue = price;
      let OUT_PRICE = price * Number(this.priceRate);
      this.form.find(item => item.fieldName == 'OUT_PRICE').initialValue = OUT_PRICE.toFixed(2);
      // console.log('价格', price, OUT_PRICE);
    },
    /* 当价格系数改变时的方法 */
    handlePriceRate(val) {
      this.priceRate = val;
      this.handlePriceCHange(this.form.find(x => x.fieldName == 'priceType').initialValue);
      // console.log(this.form.find(x => x.fieldName == 'priceType').initialValue,'获取价格9参数')
    },
    /* 点击确定 */
    async saveDialog() {
      if (this.editMode) {
        // let baseTableData = [JSON.parse(JSON.stringify(this.editData))];
        let baseTableData = this.editData;
        let formData = this.$refs.form.SUBMIT_FORM();
        let tableData = Object.assign({}, baseTableData, formData);
        console.log(tableData, '-------tableData------');
        if (this.editData.ALLOCATE_TYPE == '82121004' && tableData.OUT_QUANTITY > this.billNoQuantity) {
          return this.$notify.warning({ title: '提示信息', message: '借出出库数量不能大于还出出库数量' });
        }
        if (tableData.ITEM_ID != null || tableData.ITEM_ID != '') {
          // 判断id
          tableData.flag = 'X';
        }
        // jsonToHump(tableData);
        // let changedData = await saveOutboundOrderCreate({
        //   stockOutDate: formatdate(new Date(), 2),
        //   customerCode: tableData[0].storageCode,
        //   customerName: tableData[0].storageName,
        //   dms_table: tableData,
        //   allocateOutNo: tableData[0].allocateOutNo
        // });
        // this.$emit('reSearchTableData');
        this.$emit('handlePartAddConfirmEdit', tableData);
        this.closeDialog();
      } else {
        let submitData = this.$refs.form.SUBMIT_FORM();
        submitData.itemID = 'N';
        submitData.flag = 'A';
        // if (submitData.OUT_QUANTITY > this.activeData[0].USEABLE_STOCK) {
        //   return this.$notify.error({ title: '提示信息', message: '配件数量不可以大于可用库存' });
        // }
        let selectedData = Object.assign(this.activeData[0], submitData); // 将表单填写数据与选中的配件数据拼接为同一个对象
        let priceCoefficient = selectedData['priceCoefficient'];
        if (selectedData['priceCoefficient'] < 1) {
          if (isAuthorized('1313', '13131011')) {
            this.$emit('onConfirm', selectedData);
          } else {
            this.$notify({
              title: '警告',
              message: '价格系数小于1，您无权限添加！',
              type: 'warning'
            });
          }
        } else {
          this.$emit('onConfirm', selectedData);
        }
        console.log(selectedData, 'selectedData');
        // jsonToHump(selectedData); //将后端大写字段名转换为驼峰小写
      }
    },
    //  点击取消关闭窗口
    closeDialog() {
      this.$emit('close', false);
    },
    searchAdjustOrderAdd(val) {
      this.fetchParams1 = Object.assign({}, val, { xhrAbort: false });
    },
    searchAdjustOrderAddTwo(val) {}
  }
};
</script>
<style lang="less" scoped>
.fixBtmBtn {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
